package com.chentf.spring.annotation;

import com.chentf.spring.annotation.bean.Person;
import com.chentf.spring.annotation.config.MainConfigOfPropertyValues;
import org.junit.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;

public class IOCTest_PropertyValue {

    AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MainConfigOfPropertyValues.class);

    @Test
    public void test01() {
        printBeans(context);
        System.out.println("----------");

        Person person = (Person) context.getBean("person");
        System.out.println(person);

        // 使用@PropertySource注解读取外部配置文件中的key/value之后，是将其保存到运行的环境变量中了，所以我们也可以通过运行环境来获取外部配置文件中的值。
        ConfigurableEnvironment environment = context.getEnvironment();
        String property = environment.getProperty("person.nickName");
        System.out.println(property);

        // 关闭容器
        context.close();
    }

    private void printBeans(AnnotationConfigApplicationContext context) {
        final String[] beanDefinitionNames = context.getBeanDefinitionNames();
        for (String name : beanDefinitionNames) {
            System.out.println(name);
        }
    }
}
